package com.treeman.api.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gson.Gson;
import com.treeman.api.ApiRequestError;
import com.treeman.api.ApiRequestError.ApiError;
import com.treeman.api.security.exception.InvalidAccessTokenException;

public class ApiAuthenticationFilter implements Filter {

	private static Logger log = Logger.getLogger(ApiAuthenticationFilter.class);

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletResponse resp = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;

		SecurityContext springSecurityContext = SecurityContextHolder
				.getContext();
		if (springSecurityContext.getAuthentication() instanceof AnonymousAuthenticationToken) {
			String accessToken = (String) req.getParameter("access_token");
			if (accessToken != null) {
				try {
					ApiAuthenticationManager manager = ApiAuthenticationManager
							.getInstance();
					Authentication authentication = manager
							.authenticateUser(accessToken);
					if (authentication != null)
						springSecurityContext.setAuthentication(authentication);
				} catch (InvalidAccessTokenException e) {
					log.debug("401 Unathorized");
					ApiRequestError error = new ApiRequestError(
							ApiError.INVALID_ACCESS_TOKEN,
							"Niepoprawny access token. Jeżeli byłeś nieaktywny przez 10 min token stracił ważność.");
					String apiRequestError = new Gson().toJson(error,
							ApiRequestError.class);
					resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
					resp.getWriter().write(apiRequestError);
					return;
				}
			} else {

			}
		}

		chain.doFilter(req, resp);
		return;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
